﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CYTS.Aoyou.Framework.Cache;
using CYTS.Aoyou.Framework.CAInterface;

namespace CYTS.Aoyou.Framework.CacheAccess
{
    /// <summary>
    /// Session缓存适配器
    /// </summary>
    public class SessionCacheAdapterForRedis : CacheAdapterBase, ISessionCacheAdapter, ICacheAdapter
    {
        public SessionCacheAdapterForRedis(CacheProvider provider)
            : base(provider)
        { }

        public void Set<T>(string key, T value, TimeSpan expireTime)
        {
            List<CacheConnection> connectionList = null;
            if (!this.DicCacheConnection.TryGetValue("SessionCache", out connectionList) || connectionList.Count == 0)
            {
                throw new Exception("未找到对应的缓存连接串");
            }

            CacheConnection connection = connectionList[0];
            RedisHelper helper = new RedisHelper(connection.Host, connection.Port, Convert.ToInt32(connection.RegionName), connection.Password, this.Region);
            helper.Add(key, value, expireTime);
        }

        public T Get<T>(string key)
        {
            List<CacheConnection> connectionList = null;
            if (!this.DicCacheConnection.TryGetValue("SessionCache", out connectionList) || connectionList.Count == 0)
            {
                throw new Exception("未找到对应的缓存连接串");
            }

            CacheConnection connection = connectionList[0];
            RedisHelper helper = new RedisHelper(connection.Host, connection.Port, Convert.ToInt32(connection.RegionName), connection.Password, this.Region);
            return helper.Get<T>(key);
        }

        public void Remove(string key)
        {
            List<CacheConnection> connectionList = null;
            if (!this.DicCacheConnection.TryGetValue("SessionCache", out connectionList) || connectionList.Count == 0)
            {
                throw new Exception("未找到对应的缓存连接串");
            }

            CacheConnection connection = connectionList[0];
            RedisHelper helper = new RedisHelper(connection.Host, connection.Port, Convert.ToInt32(connection.RegionName), connection.Password, this.Region);
            helper.Remove(key);
        }
    }
}
